package com.seeyon.apps.cxgd.event;

import com.alibaba.fastjson.JSON;
import com.seeyon.apps.addressbook.manager.AddressBookCustomerFieldInfoManager;
import com.seeyon.apps.addressbook.manager.AddressBookManager;
import com.seeyon.apps.addressbook.po.AddressBook;
import com.seeyon.apps.cxgd.kit.HttpKit;
import com.seeyon.apps.cxgd.kit.LogKit;
import com.seeyon.apps.cxgd.kit.SameBusinessTripKit;
import com.seeyon.apps.cxgd.kit.StrKit;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.formula.FormulaUtil;
import com.seeyon.ctp.common.log.CtpLogFactory;
import com.seeyon.ctp.organization.bo.V3xOrgMember;
import com.seeyon.ctp.organization.event.AddMemberEvent;
import com.seeyon.ctp.organization.event.UpdateMemberEvent;
import com.seeyon.ctp.organization.manager.OrgManager;
import com.seeyon.ctp.util.annotation.ListenEvent;
import org.apache.commons.logging.Log;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


public class MemberAddOrUpdateListenerEvent {

    private static final Log log = CtpLogFactory.getLog(MemberAddOrUpdateListenerEvent.class);
    private OrgManager orgManager = (OrgManager) AppContext.getBean("orgManager");
    private AddressBookCustomerFieldInfoManager addressBookCustomerFieldInfoManager = (AddressBookCustomerFieldInfoManager) AppContext.getBean("addressBookCustomerFieldInfoManager");

    @ListenEvent(event = AddMemberEvent.class, async = true)
    public void addMember(AddMemberEvent event) {
        try {
            log.info("进入添加人员监听-------------------------------------");
            String same_business_trip_url = StrKit.str(FormulaUtil.getVar("same_business_trip_url"));
            String secret = StrKit.str(FormulaUtil.getVar("tcSecret"));
            V3xOrgMember v3xOrgMember = event.getMember();
            String accessToken = SameBusinessTripKit.getSameBusinessTripToken();
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("accessToken", accessToken);
            map.put("isEncrypt", false);
            map.put("random", UUID.randomUUID().toString());
            map.put("timestamp", System.currentTimeMillis());
            Map<String, Object> param_map = new HashMap<String, Object>();
            param_map.put("outEmployeeId", StrKit.str(v3xOrgMember.getId()));
            String code = StrKit.str(v3xOrgMember.getCode());
            AddressBook addressBook = addressBookCustomerFieldInfoManager.getByMemberId(v3xOrgMember.getId());
            String name = "";
            String extAttr5 = StrKit.str(addressBook.getExtAttr5());
            if ("".equals(extAttr5)) {
                name = StrKit.str(v3xOrgMember.getName());
            } else {
                name = extAttr5;
            }
            param_map.put("employeeCode", code);
            param_map.put("surName", name);
            param_map.put("employeeType", 0);
            String gerder = StrKit.str(v3xOrgMember.getGender());
            if ("2".equals(gerder)) {
                param_map.put("gender", "0");
            } else if ("1".equals(gerder)) {
                param_map.put("gender", gerder);
            } else {
                param_map.put("gender", "");
            }
            param_map.put("email", StrKit.str(v3xOrgMember.getEmailAddress()));
            param_map.put("mobile", StrKit.str(v3xOrgMember.getTelNumber()));
            param_map.put("reservationType", 0);
            String levelId = StrKit.str(v3xOrgMember.getOrgLevelId());
            String levelName = orgManager.getLevelById(Long.parseLong(levelId)).getName();
            param_map.put("positionLevelName", levelName);
            String deptId = StrKit.str(v3xOrgMember.getOrgDepartmentId());
            String deptName = orgManager.getDepartmentById(Long.parseLong(deptId)).getName();
            param_map.put("outDepartId", deptId);
            param_map.put("departName", deptName);
            boolean enabled = v3xOrgMember.getEnabled();
            if (enabled) {
                param_map.put("workingState", 1);
            } else {
                param_map.put("workingState", 0);
            }
            Date birthday = v3xOrgMember.getBirthday();
            if (birthday != null) {
                param_map.put("birthday", new SimpleDateFormat("yyyy-MM-dd").format(birthday));
            } else {
                param_map.put("birthday", "");
            }
            map.put("param", param_map);
            String data_json = JSON.toJSONString(map);
            String dataMd5 = SameBusinessTripKit.stringToMD5(data_json);
            String signStr = dataMd5 + secret;
            String sign = SameBusinessTripKit.stringToMD5(signStr);
            String url = same_business_trip_url + "/openapi/api/Employee/SyncEmployeeInfo?sign=" + sign;
            String result = HttpKit.httpsPost(url, new HashMap<String, Object>(), data_json);
            log.info("同程人员新增请求结果:" + result);
            LogKit.addLog(name + "_" + code, "同程人员新增", data_json, result);
        } catch (Exception e) {
            log.error("同程人员新增失败:", e);
        }

    }

    @ListenEvent(event = UpdateMemberEvent.class, async = true)
    public void updateMember(UpdateMemberEvent event) {
        try {
            log.info("进入更新人员监听-------------------------------------");
            String same_business_trip_url = StrKit.str(FormulaUtil.getVar("same_business_trip_url"));
            String secret = StrKit.str(FormulaUtil.getVar("tcSecret"));
            V3xOrgMember v3xOrgMember = event.getMember();
            String accessToken = SameBusinessTripKit.getSameBusinessTripToken();
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("accessToken", accessToken);
            map.put("isEncrypt", false);
            map.put("random", UUID.randomUUID().toString());
            map.put("timestamp", System.currentTimeMillis());
            Map<String, Object> param_map = new HashMap<String, Object>();
            param_map.put("outEmployeeId", StrKit.str(v3xOrgMember.getId()));
            String code = StrKit.str(v3xOrgMember.getCode());
            AddressBook addressBook = addressBookCustomerFieldInfoManager.getByMemberId(v3xOrgMember.getId());
            String name = "";
            if (addressBook == null) {
                name = StrKit.str(v3xOrgMember.getName());
            } else {
                String extAttr5 = StrKit.str(addressBook.getExtAttr5());
                if ("".equals(extAttr5)) {
                    name = StrKit.str(v3xOrgMember.getName());
                } else {
                    name = extAttr5;
                }
            }

            param_map.put("employeeCode", code);
            param_map.put("surName", name);
            param_map.put("modifyType", 1);
            param_map.put("employeeType", 0);
            String gerder = StrKit.str(v3xOrgMember.getGender());
            if ("2".equals(gerder)) {
                param_map.put("gender", "0");
            } else if ("1".equals(gerder)) {
                param_map.put("gender", gerder);
            } else {
                param_map.put("gender", "");
            }
            param_map.put("email", StrKit.str(v3xOrgMember.getEmailAddress()));
            param_map.put("mobile", StrKit.str(v3xOrgMember.getTelNumber()));
            param_map.put("reservationType", 0);
            String levelId = StrKit.str(v3xOrgMember.getOrgLevelId());
            String levelName = orgManager.getLevelById(Long.parseLong(levelId)).getName();
            param_map.put("positionLevelName", levelName);
            String deptId = StrKit.str(v3xOrgMember.getOrgDepartmentId());
            String deptName = orgManager.getDepartmentById(Long.parseLong(deptId)).getName();
            param_map.put("outDepartId", deptId);
            param_map.put("departName", deptName);
            boolean enabled = v3xOrgMember.getEnabled();
            if (enabled) {
                param_map.put("workingState", 1);
            } else {
                param_map.put("workingState", 0);
            }
            Date birthday = v3xOrgMember.getBirthday();
            if (birthday != null) {
                param_map.put("birthday", new SimpleDateFormat("yyyy-MM-dd").format(birthday));
            } else {
                param_map.put("birthday", "");
            }
            map.put("param", param_map);
            String data_json = JSON.toJSONString(map);
            String dataMd5 = SameBusinessTripKit.stringToMD5(data_json);
            String signStr = dataMd5 + secret;
            String sign = SameBusinessTripKit.stringToMD5(signStr);
            String url = same_business_trip_url + "/openapi/api/Employee/SyncEmployeeInfo?sign=" + sign;
            String result = HttpKit.httpsPost(url, new HashMap<String, Object>(), data_json);
            log.info("同程人员更新请求结果:" + result);
            LogKit.addLog(name + "_" + code, "同程人员更新", data_json, result);
        } catch (Exception e) {
            log.error("同程人员更新失败:", e);
        }
    }

}
